package net.htjs.juc.chapter04;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
public class ExerciseTransfer {

    //Radmon为线程安全
    static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }

    /**
     * 15:18:21.387 [main] INFO net.htjs.juc.chapter4.ExerciseTransfer - total:2035
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t1 = new Thread(() -> {
                a.transfer(b, randomAmount());
            });
            t1.start();
            threadList.add(t1);
            Thread t2 = new Thread(() -> {
                b.transfer(a, randomAmount());
            });
            t2.start();
            threadList.add(t2);
        }
        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        log.info("total:{}", (a.getMoney() + b.getMoney()));
    }



    static class Account {

        private int money;

        public Account(int money) {
            this.money = money;
        }

        public int getMoney() {
            return money;
        }

        public void setMoney(int money) {
            this.money = money;
        }

        public void transfer(Account target, int amount) {
            synchronized (Account.class) {
                if (this.money >= amount) {
                    this.setMoney(this.getMoney() - amount);
                    target.setMoney(target.getMoney() + amount);
                }
            }
        }
    }
}
